package org.example.test4;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;

public class t4 {
    public static void main(String[] args) {
        Shop shop = new Shop();
        Producer pro = new Producer(shop);
        Cousumer cou = new Cousumer(shop);
        new Thread(pro).start();
        new Thread(cou).start();
    }
}

class Product {}

class Shop {
    private static final int BUFFER_SIZE = 10;
    private List<Product> list = new ArrayList<>();
    private Semaphore produceSemaphore = new Semaphore(BUFFER_SIZE);
    private Semaphore consumeSemaphore = new Semaphore(0);

    public void produ() {
        try {
            produceSemaphore.acquire();
            synchronized (this) {
                Product product = new Product();
                list.add(product);
                System.out.println("producing");
                System.out.println("amount of product is " + list.size());
            }
            consumeSemaphore.release();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void cousu() {
        try {
            consumeSemaphore.acquire();
            synchronized (this) {
                list.remove(0);
                System.out.println("comsuming");
                System.out.println("amount of product is " + list.size());
            }
            produceSemaphore.release();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class Cousumer implements Runnable {
    private Shop shop;

    public Cousumer(Shop shop) {
        this.shop = shop;
    }

    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
                shop.cousu();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

class Producer implements Runnable {
    private Shop shop;

    public Producer(Shop shop) {
        this.shop = shop;
    }

    public void run() {
        while (true) {
            try {
                Thread.sleep(1000);
                shop.produ();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
